package com.shareach.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.benayn.ustyle.Reflecter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;
import com.shareach.common.BaseQueryOrder;
import com.shareach.dao.redis.impl.DeployRDao;
import com.shareach.dao.redis.impl.DeployRDao.DeployType;
import com.shareach.domain.BaseShopDomain;
import com.shareach.domain.BizActivityShopDomain;
import com.shareach.domain.BizCardDomain;
import com.shareach.domain.BizTuanShopDomain;
import com.shareach.service.BaseBankService;
import com.shareach.service.BaseCityService;
import com.shareach.service.BaseShopService;
import com.shareach.service.BizActivityService;
import com.shareach.service.BizActivityShopService;
import com.shareach.service.BizCardService;
import com.shareach.service.BizTuanService;
import com.shareach.service.BizTuanShopService;
import com.shareach.util.JsonUtil;
import com.shareach.web.basic.Answer;

@Controller("wshop")
@RequestMapping("/wshop")
public class ShopController extends BaseController {

	@Autowired
	BaseShopService shopService;
	@Autowired
	BizTuanShopService tuanShopService;
	@Autowired
	BizTuanService tuanService;
	@Autowired
	BizCardService cardService;
	@Autowired
	BaseBankService bankService;
	@Autowired
	BizActivityService activityService;
	@Autowired
	BizActivityShopService activityShopService;
	@Autowired
	BaseCityService cityService;
	@Autowired
	private DeployRDao deployRDao;

	@RequestMapping(value = "/shop/upload.htm", method = RequestMethod.POST)
	public ModelAndView shopImgUpload(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("file") MultipartFile file) {

		if (!file.isEmpty()) {
			String newFileName = uploadFile(request, file, DeployType.Shop.getDesc());
			// update shop
			Long shopId = Long.valueOf(request.getParameter("shopId"));
			BaseShopDomain shopDom = new BaseShopDomain();
			shopDom.setId(shopId);
			shopDom.setImg(DeployType.Shop.getCode() + "/" + newFileName);
			shopService.update(shopDom);
			resetRedisDeployed(DeployType.Shop, shopId);
			return new ModelAndView(new RedirectView(request.getContextPath() + "/wshop/shopdetail/index.htm?shopId="
					+ shopId));
		}
		return new ModelAndView();
	}

	@RequestMapping(value = "/shop/index.htm")
	public ModelAndView shop(HttpServletRequest request, Integer hasdeploy, Integer hasimg, Integer hastel,
			Integer hasweibo, Integer hasaddr, Integer hasloc, Integer hasprice, Long id, String brand, String name) {
		ModelAndView mv = new ModelAndView("admin/shop/shop/index");
		BaseQueryOrder order = new BaseQueryOrder();
		order.setNumber(getPageNo(request).toString());
		order.setPageSize(getPageSize(request));
		order.addSort("_id", Order.DESCENDING.toString());

		BaseShopDomain domain = new BaseShopDomain();
		addCriteria(domain, hasdeploy, "deployTime");
		addCriteria(domain, hastel, "tels");
		addCriteria(domain, hasimg, "img");
		addCriteria(domain, hasweibo, "weiboId");
		addCriteria(domain, hasaddr, "addr");
		addCriteria(domain, hasloc, "loc");
		addCriteria(domain, hasprice, "price");

		if (StringUtils.isNotEmpty(brand)) {
			domain.setBrand(brand);
			mv.addObject("brand", brand);
		}
		if (null != id) {
			domain.setId(id);
			mv.addObject("id", id);
		}
		if (StringUtils.isNotEmpty(name)) {
			domain.addRegexMap(name.trim(),"name");
		}

		Page<BaseShopDomain> shops = shopService.getPageResult(domain, order);

		Map<String, Integer> conditions = new HashMap<String, Integer>();
		conditions.put("deploy", null == hasdeploy ? 1 : hasdeploy);
		conditions.put("img", null == hasimg ? 1 : hasimg);
		conditions.put("tels", null == hastel ? 1 : hastel);
		conditions.put("weiboId", null == hasweibo ? 1 : hasweibo);
		conditions.put("addr", null == hasaddr ? 1 : hasaddr);
		conditions.put("loc", null == hasloc ? 1 : hasloc);
		conditions.put("price", null == hasprice ? 1 : hasprice);
		mv.addObject("conditions", conditions);
		mv.addObject("result", shops);
		mv.addObject("name", name==null?null:name.trim());
		return mv;
	}

	@RequestMapping(value = "/shop/edit.htm")
	public ModelAndView shopEdit(HttpServletRequest request, HttpServletResponse response, String shopId,
			BaseShopDomain domain) {
		ModelAndView view = new ModelAndView("admin/shop/detail/tplShopEdit");

		if (domain == null || domain.getId() == null) {
			// redirect
			Long parabrand = Long.valueOf(shopId);
			BaseShopDomain shop = shopService.getById(parabrand);
			view.addObject("shop", shop);
			return view;
		} else {
			Answer<Object> r = new Answer<Object>();
			try {
				BaseShopDomain shop = shopService.getById(domain.getId());
				BaseShopDomain change = shop.compareTo(domain);
				change.setId(domain.getId());
				// edit
				domain.setName(null);// 此属性不可更新
				shopService.update(change);
				// update redis
				resetRedisDeployed(DeployType.Shop, domain.getId());
				this.outText(response, JsonUtil.jsonFromObject(r));
			} catch (Exception e) {
				r.setCmd(-1);
				r.setMsg("System Error");
				this.outText(response, JsonUtil.jsonFromObject(r));
			}
			return view;
		}

	}

	@RequestMapping(value = "/shopdetail/index.htm")
	public ModelAndView shopdetail(HttpServletRequest request, Long shopId) {
		ModelAndView mv = new ModelAndView("admin/shop/detail/index");

		/*
		 * 
		 * shop cityInfo<city> tuans list<tuanshop> tuanInfo<tuan> cards
		 * list<card> bankInfo<bank> activities list<activityshop>
		 * activityInfo<activity>
		 */

		// shop
		BaseShopDomain domShop = shopService.getById(shopId);
		Map<String, Object> shop = asDynabean(domShop);

		// city
		shop.put("cityInfo", asDynabean(cityService.getById(domShop.getCity())));

		// tuans
		List<Map<String, Object>> tuans = Lists.newArrayList();
		BizTuanShopDomain qryTuanShop = new BizTuanShopDomain();
		qryTuanShop.setShopId(shopId);
		List<BizTuanShopDomain> domShopTuans = tuanShopService.getList(qryTuanShop);

		for (BizTuanShopDomain t : domShopTuans) {
			Map<String, Object> domTuanShop = asDynabean(t);
			domTuanShop.put("tuanInfo", asDynabean(tuanService.getById(t.getTuanId())));
			tuans.add(domTuanShop);
		}
		shop.put("tuans", tuans);

		// card
		List<Map<String, Object>> cards = Lists.newArrayList();
		BizCardDomain qryCard = new BizCardDomain();
		qryCard.setShopId(shopId);
		List<BizCardDomain> domCards = cardService.getList(qryCard);

		for (BizCardDomain c : domCards) {
			Map<String, Object> domCard = asDynabean(c);
			domCard.put("bankInfo", asDynabean(bankService.getById(Longs.tryParse(c.getSite()))));
			cards.add(domCard);
		}
		shop.put("cards", cards);

		// activity
		List<Map<String, Object>> activites = Lists.newArrayList();
		BizActivityShopDomain qryActivityShop = new BizActivityShopDomain();
		qryActivityShop.setShopId(shopId);
		List<BizActivityShopDomain> domActivityShops = activityShopService.getList(qryActivityShop);
		for (BizActivityShopDomain a : domActivityShops) {
			Map<String, Object> domActivityShop = asDynabean(a);
			domActivityShop.put("activityInfo", asDynabean(activityService.getById(a.getActivityId())));
			activites.add(domActivityShop);
		}

		shop.put("activites", activites);
		mv.addObject("shop", shop);

		return mv;
	}

	private Map<String, Object> asDynabean(Object obj) {
		if (null == obj) {
			return Maps.newHashMap();
		}

		return Reflecter.from(obj).asMap();
	}

	private void addCriteria(BaseShopDomain domain, Integer val, String propName) {
		if (null == val) {
			return;
		}
		switch (val) {
		case 2:
			domain.addFieldExists(propName);
			break;
		case 3:
			domain.addFieldNoneExists(propName);
			break;
		}
	}

	public void resetRedisDeployed(DeployType type, Long id) {
		if (deployRDao.isDeployed(type, id)) {
			deployRDao.setUndeployed(type, id);
		}
	}
}
